package com.lzy.managersystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.managersystem.pojo.Role;
import com.lzy.managersystem.service.RoleMenuService;
import com.lzy.managersystem.service.RoleService;
import com.lzy.managersystem.tools.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/role")
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @GetMapping("/")
    public Result selectAll() {
        List<Role> list = roleService.getAllUser();
        return Result.success(list);
    }

    @PostMapping("/inster")
    public Result insertUser(@RequestBody Role role) {
        System.out.println(role);
        int flag = roleService.insterUser(role);
        return Result.success(flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        int flag = roleService.deleteUser(id);
        return Result.success(flag);
    }

    @PostMapping("/del/batch")
    public Result deleteBatchUser(@RequestBody List<Integer> ids) {
        int flag = roleService.deleteBatchUser(ids);
        return Result.success(flag);
    }

    @PutMapping("/")
    public Result UpdataUser(@RequestBody Role role) {
        int flag = roleService.updateUser(role);
        return Result.success(flag);
    }


    /**
     * 绑定角色和菜单的关系
     *
     * @param roleId  角色id
     * @param menusid 菜单id
     * @return
     */
    @PostMapping("/rolemenu/{roleId}")
    public Result selectRoleMenu(@PathVariable("roleId") Integer roleId, @RequestBody List<Integer> menusid) {
        roleMenuService.deleteByRoleid(roleId, menusid);
        return Result.success();
    }

    /**
     * 查询roleId的menuid
     *
     * @param roleId 角色id
     * @return
     */
    @GetMapping("/rolemenu/{roleId}")
    public Result selectRoleMenuid(@PathVariable("roleId") Integer roleId) {
        List<Integer> list = roleMenuService.selectByroleid(roleId);
        return Result.success(list);
    }

    //查询所有用户（分页）
    @GetMapping("/page")
    public Result selectUserPage(@RequestParam Integer pageSize,
                                 @RequestParam Integer pageNum,
                                 @RequestParam(defaultValue = "") String name
    ) {
        IPage<Role> roleIPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Role> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("name", name);
//        userQueryWrapper.orderByDesc("id");
        return Result.success(roleService.page(roleIPage, userQueryWrapper));

    }
}
